package com.wbj.vpdirection.viewpager

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.viewpager.widget.PagerAdapter
import com.wbj.vpdirection.mode.AngleData
import com.wbj.vpdirection.R
import com.wbj.vpdirection.util.AltitudeUtil

class DirectionPageAdapter(val context: Context,val list:MutableList<AngleData>): PagerAdapter() {
    
    private val mInflater:LayoutInflater by lazy {  LayoutInflater.from(context) }
    var lastPosition = 0
    var currentPosition = 0
    var currentView:View? = null
    
    override fun getCount(): Int {
        return list.size
    }
    
    override fun isViewFromObject(view: View, o: Any): Boolean {
        return view == o
    }
    
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view = mInflater.inflate(R.layout.item_direct,null,false)
        container.addView(view)
        setSelectItemState(container,position,view)
        return view
    }
    
    private fun setSelectItemState(container: ViewGroup, position: Int,view :View) {
        val realPosition = position%list.size
        val angle = list[realPosition]
        view.setOnClickListener{
            Toast.makeText(context,"${realPosition}",Toast.LENGTH_SHORT).show()
        }
        view.findViewById<TextView>(R.id.tvLeftAngle).text = angle.leftAngle.toString()
        view.findViewById<TextView>(R.id.tvRightAngle).text = angle.rightAngle.toString()
        val centerTextView = view.findViewById<TextView>(R.id.tvCenterAngle)
        centerTextView.text = when (angle.centerAngle) {
            0 -> "北"
            45 -> "东北"
            90 -> "东"
            135 -> "东南"
            180 -> "南"
            225 -> "西南"
            270 -> "西"
            315 -> "西北"
            else -> angle.toString()
        }
        centerTextView.isSelected  = angle.isSelect
    }
    
    override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
        super.setPrimaryItem(container, position, `object`)
        this.currentView.let {
            val tvCenterView = it?.findViewById<TextView>(R.id.tvCenterAngle)
            tvCenterView?.setTextColor(Color.parseColor("#FFFEFF"))
            tvCenterView?.setTextSize(AltitudeUtil.dipToPx(context,20f).toFloat())
        }
        (`object` as View).let {
            val tvCenterView = it?.findViewById<TextView>(R.id.tvCenterAngle)
            tvCenterView?.setTextColor(Color.parseColor("#4BFEC7"))
            tvCenterView?.setTextSize(AltitudeUtil.dipToPx(context,24f).toFloat())
        }
        this.currentView = `object`
    }
    
    override fun destroyItem(container: ViewGroup, position: Int, o: Any) {
        container.removeView(o as View?)
    }
    
}